<template>
  <div id="conentpage" class="rightBodyContent">
    <div class="rightBodyContent-in">
      <el-button type="primary" plain @click="backlist" size="small" v-if="editId"><i class="el-icon-back"></i>返回列表
      </el-button>
      <el-row class="warp">
        <el-col :span="24" class="warp-main">
          <el-form ref="infoForm" :model="infoForm" :rules="rules" label-width="140px">
            <el-form-item label="问卷标题:" prop="title">
              <el-input v-model="infoForm.title" placeholder="填写投票名称"></el-input>
            </el-form-item>
            <el-form-item label="问卷描述:" prop="description">
              <quill-editor v-model="infoForm.description"
                            ref="myQuillEditor"
                            class="editer"
                            :options="editorOption" @ready="onEditorReady($event)" placeholder="填写通知内容">
              </quill-editor>
            </el-form-item>
            <el-form-item label="承诺书:" prop="commitment">
              <el-radio-group v-model="commitment" @change="radiochangeTab">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
              <el-button @click="commitmentBtnFn" size="small" class="ml-20" v-if="commitment==1">编辑承诺书内容</el-button>
            </el-form-item>
            <el-form-item label="问卷范围:" prop="title">
              <el-radio-group v-model="infoForm.type" @change="radiochangeTab">
                <el-radio :label="0">全校</el-radio>
                <el-radio :label="1">特定年段</el-radio>
                <el-radio :label="2">特定班级</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="请选择年段:" v-if="infoForm.type==1">
              <!--<el-select v-model="value1" multiple placeholder="请选择" style="width: 100%;">-->
              <!--<el-option-->
              <!--v-for="item in sectionList"-->
              <!--:key="item.id"-->
              <!--:label="item.section_name"-->
              <!--:value="item.id">-->
              <!--</el-option>-->
              <!--</el-select>-->
<!--              <sectionInputMore @changeSectionMore="changeSectionMore" :value1.sync="value1"></sectionInputMore>-->
              <sectionInput :sectionId.sync="infoForm.section_id"></sectionInput>
            </el-form-item>
            <el-form-item label="请选择班级:" v-if="infoForm.type==2">
              <div style="display: flex;">
                <sectionInput @changeSection="changeSection" :sectionId.sync="infoForm.section_id"></sectionInput>
                <classInput @changeClass="changeClass" :sectionId.sync="infoForm.section_id"
                            :classId.sync="infoForm.class_id"></classInput>
              </div>
            </el-form-item>
            <el-form-item label="是否选择特定学生:" v-if="infoForm.class_id">
              <el-radio-group @change="staduentchange" v-model="studentRadio">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择特定学生:" v-if="studentRadio==1">
              <el-button type="primary" @click="chooseStudent" class="mb-10" size="small">选择特定学生</el-button>
              <div>
                <el-tag
                    :key="tag"
                    v-for="(tag,index) in dynamicTags"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index)"
                    class="mr-10"
                >{{ tag }}
                </el-tag>
              </div>
            </el-form-item>
            <el-form-item label="问卷开始时间:" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date"
                                placeholder="开始时间"
                                v-model="infoForm.start_time"
                                :picker-options="pickerOptions1"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="问卷结束时间:" prop="end_time">
              <el-col :span="11">
                <el-date-picker type="date"
                                placeholder="结束时间"
                                v-model="infoForm.end_time"
                                :picker-options="pickerOptions1"
                                format="yyyy-MM-dd"
                                value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-form-item>
            <el-form-item label="问卷内容:">
              <div class="iconlist questionlist" v-for="(item,i) in infoForm.body">
                <div style="display: flex;align-items: center;">{{ i + 1 }}.
                  <el-input v-model="infoForm.body[i].content" placeholder="填写问卷内容"></el-input>
                  <i class="el-icon-circle-plus-outline iconadd addicon" @click="onAdd(index)" v-if="i==0"></i>
                  <i class="el-icon-error iconadd detelicon" @click="onDetel(i)" v-else></i>
                </div>
                <div>
                  问卷回答类型：
                  <el-radio-group v-model="infoForm.body[i].type" @change="radioChange(i)">
                    <el-radio :label="1">单选项</el-radio>
                    <el-radio :label="2">多选项</el-radio>
                    <el-radio :label="3">输入框</el-radio>
                  </el-radio-group>
                  <span class="infoline">(选项：用户选择ABCD选项；输入框：用户自行输入文字内容)</span>
                </div>
                <!--<div>-->
                <!--老师是否能查看家长反馈明细：-->
                <!--<el-radio-group v-model="infoForm.body[i].show_status">-->
                <!--<el-radio :label="0">否</el-radio>-->
                <!--<el-radio :label="1">是</el-radio>-->
                <!--</el-radio-group>-->
                <!--<span class="infoline">(各个家长反馈后，教师可查看详细的反馈)</span>-->
                <!--</div>-->
                <div>
                  本题是否需要签订承诺书：
                  <el-radio-group v-model="infoForm.body[i].show_status" @change="commitmentChange(i)">
                    <el-radio :label="0">否</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                  <span class="infoline">(家长需要签名，选项只能填写是否)</span>
                </div>
                <!-- 1单 2 多 3输入 -->
                <div class="questionline" v-if="infoForm.body[i].type==1||infoForm.body[i].type==2">
                  <div v-for="(item,indexs) in infoForm.body[i].option" class="questionline-list">
                    <p>
                      {{ qustionCheck[indexs] }}.
                      <el-input v-model="infoForm.body[i].option[indexs].text" placeholder="填写选项内容"></el-input>
                      <span v-if="indexs==0">
                          <i class="el-icon-circle-plus-outline iconadd addicon" @click="addlinebox(i)"
                             v-if="infoForm.body[i].option.length<7"></i>
                          </span>
                      <i class="el-icon-error iconadd detelicon" @click="detellinebox(i, indexs)" v-else></i>
                    </p>
                    <p>
                      是否添加输入框：
                      <el-radio-group v-model="infoForm.body[i].option[indexs].type">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="2">否</el-radio>
                      </el-radio-group>
                    </p>
                    <p>
                      本选项是否需要签订承诺书：
                      <el-radio-group v-model="infoForm.body[i].option[indexs].is_commitment">
                        <el-radio label="1">是</el-radio>
                        <el-radio label="0">否</el-radio>
                      </el-radio-group>
                    </p>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit" size="small">修改并保存</el-button>
              <el-button @click="backlist" size="small">返回</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </div>
    <studentMultiple :visible.sync="studentVisible" @studentFn="studentFn" :userclassId="infoForm.class_id"
                     :usersectionId="infoForm.section_id" :dynamicTagsArray="dynamicTagsArray"></studentMultiple>
    <commitment :visible.sync="commitmentVisible" @commitmentEditFn="commitmentEditFn" :editId="editId"
                :commitment="infoForm.commitment"></commitment>
    <qustionUser :visible.sync="qustionUserVisible" :optionId="optionId"></qustionUser>
  </div>
</template>

<script>
// import {yeartime} from '../../assets/js/common'
import classInput from '@/components/template/classInput.vue'
import sectionInput from '@/components/template/sectionInput.vue'
import sectionInputMore from '@/components/template/sectionInputMore.vue'
import studentMultiple from '@/components/dialog/studentMultiple.vue'
import commitment from '@/components/dialog/commitment.vue'
import qustionUser from '@/components/dialog/qustionUser.vue'
import {pagination} from '@/utils/util.js'
import api from '@/utils/api.js'

import {quillEditor} from 'vue-quill-editor' // 调用编辑器
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import {questionAdd} from '@/api/admin/parents_questionnaire'

export default {
  components: {
    quillEditor,
    classInput,
    sectionInput,
    studentMultiple,
    sectionInputMore,
    commitment,
    qustionUser
  },
  data() {
    return {
      page: {
        pageindex: pagination.pageIndex,
        pagesize: pagination.pageSize,
        total: pagination.total
      },
      qustionCheck: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
      editorOption: {
        modules: {
          toolbar: [['bold', 'underline', 'color', 'clean', 'image']]
        }
      },
      tableStripe: true, // 是否斑马栏
      tableBorder: true, // 单元格右边边框
      dialogTableVisible: false,
      infoForm: {
        body: [{
          'content': null,
          'type': '1',
          'show_status': 0,
          'option': [{text: '', type: '2', is_commitment: '0'}]
        }],
        title: '',
        class_id: '',
        section_id: '',
        type: 0,
        description: '',
        start_time: yeartime(new Date()),
        end_time: yeartime(new Date()),
        student_id: 0,
        commitment: '' // 承诺书
      },
      commitment: 0, // 承诺书 0否 1是
      commitmentVisible: false,
      qustionUserVisible: false,
      // 表单验证
      rules: {
        title: [
          {required: true, message: '填写问卷标题', trigger: 'blur'}
        ]
      },
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() < Date.now() // - 8.64e7
        }
      },
      arryList: null,
      usersName: null,
      editId: this.$route.query.editId,
      listCheck: [],
      value1: [],
      sectionList: [],
      classesList: [],
      oldClass: {}, // 未处理的班级
      oldsection: {}, // 未处理的年段
      editClass_id: [],
      editsection_id: [],
      studentRadio: 0,
      studentVisible: false,
      dynamicTags: [],
      dynamicTagsId: [],
      dynamicTagsArray: {},
      editBody: null,
      optionId: 0,
      deleteId: []
    }
  },
  watch: {
    '$route'(to, from) {
      // 这样就可以获取到变化的参数了，然后执行参数变化后相应的逻辑就行了
      console.log('路由参数变化', this.$route.query, this.$route.query.editId, !this.$route.query.editId)
      if (!this.$route.query.editId) {
        this.editId = ''
      }
    }
  },
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill
    }
  },
  created() {

  },
  mounted() {
    if (this.editId) {
      this.Inint()
    }
  },
  methods: {
    Inint() {
      this.$fetch(api.admin_questionnaire_detail, {id: this.editId}).then((response) => {
        if (response.code === 0) {
          this.infoForm.start_time = response.vo.start_time
          this.infoForm.end_time = response.vo.end_time
          this.infoForm.title = response.vo.title
          this.listCheck = response.list
          this.infoForm.type = response.vo.type
          // this.infoForm.class_id = response.vo.class_id
          this.infoForm.description = response.vo.description
          this.infoForm.commitment = response.vo.commitment
          if (response.vo.commitment) {
            this.commitment = 1
          }
          // 0全校 1特定年段 2特定班级
          if (Number(response.vo.type) === 1) {
            // this.editsection_id = response.vo.section_id
            this.infoForm.section_id = response.vo.section_id[0].id
          } else if (Number(response.vo.type) === 2) {
            // this.editClass_id = response.vo.class_id
            this.infoForm.section_id = response.vo.section_id[0].id
            this.infoForm.class_id = response.vo.class_id[0].id
          }
          this.editBody = response.vo
          this.infoForm.body = response.list
        } else {
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    onEditorReady(editor) {
    },
    onAdd(index) {
      this.infoForm.body.splice(index+1, 0, {
        'content': null,
        'type': '1',
        'show_status': 0,
        'option': [{text: '', type: '2', is_commitment: '0'}]
      })
      // this.infoForm.body.push({
      //   'content': null,
      //   'type': '1',
      //   'show_status': 0,
      //   'option': [{text: '', type: '2', is_commitment: '0'}]
      // })
    },
    addlinebox(i) {
      this.infoForm.body[i].option.push({text: '', type: '2', is_commitment: '0'})
    },
    detellinebox(i, index) {
      this.infoForm.body[i].option.splice(index, 1)
    },
    onDetel(index) {
      console.log('this.infoForm.body:', this.infoForm.body)
      if (this.infoForm.body[index].id) {
        this.deleteId.push(this.infoForm.body[index].id)
      }
      this.infoForm.body.splice(index, 1)
    },
    // 设置默认选中
    checked() {
      console.log('默认选项判断', this.applyBookBox)
      for (let i = 0; i < this.arryList.length; i++) {
        if (this.applyBookBox[this.arryList[i].id]) {
          console.log('数值', i)
          this.$refs.table.toggleRowSelection(this.arryList[i], true)
        }
      }
    },
    radioChange(e) {
      if (this.infoForm.body[e].type == 3) {
        this.infoForm.body[e].option = []
      } else {
        this.infoForm.body[e].option = [{text: '', type: '2', is_commitment: '0'}]
      }
    },
    backlist() {
      this.$router.go(-1)
    },
    radiochangeTab(option) {
      this.infoForm.section_id = ''
      this.section_id = ''
      this.infoForm.class_id = ''
      this.value1 = []
    },
    onSubmit() {
      // 提交 this.$refs.infoForm.validate，这是表单验证
      console.log('数据提交', this.infoForm, this.value1)
      if (!this.infoForm.title) {
        this.$message({
          message: '请填写问卷标题',
          type: 'error'
        })
        return
      }
      if (this.commitment === 1 && !this.infoForm.commitment) {
        this.$message({
          message: '请填写承诺书内容',
          type: 'error'
        })
        return
      }
      // 1单 2 多 3输入
      for (let i in this.infoForm.body) {
        if (!this.infoForm.body[i].content) {
          this.$message({
            message: '请填写问卷内容',
            type: 'error'
          })
          return
        }
        if (this.infoForm.body[i].type == 1 || this.infoForm.body[i].type == 2) {
          for (let j in this.infoForm.body[i].option) {
            if (!this.infoForm.body[i].option[j].text) {
              console.log('none')
              this.$message({
                message: '请填写问卷选项',
                type: 'error'
              })
              return
            }
          }
        }
      }
      if (Number(this.infoForm.type) === 1 && this.value1.length) {
        this.infoForm.section_id = this.value1.join(',')
      }
      if (Number(this.infoForm.type) === 1 && !this.infoForm.section_id) {
        this.$message({
          message: '请选择特定年段',
          type: 'error'
        })
        return
      }
      if (Number(this.infoForm.type) === 2 && !this.infoForm.class_id) {
        this.$message({
          message: '请选择特定班级',
          type: 'error'
        })
        return
      }
      if (this.studentRadio === 1 && this.infoForm.student_id === 0) {
        this.$message({
          message: '请选择特定学生',
          type: 'error'
        })
        return
      }
      let data_ = {}
      let body_ = this.infoForm.body
      for (let i in body_) {
        if (body_[i].type !== 3) {
          for (let j in body_[i].option) {
            body_[i].option[j]['index'] = this.qustionCheck[j]
          }
        }
      }
      data_.title = this.infoForm.title
      data_.type = this.infoForm.type
      data_.class_id = this.infoForm.class_id
      data_.start_time = this.infoForm.start_time
      data_.end_time = this.infoForm.end_time
      data_.body = JSON.stringify(body_)
      data_.section_id = this.infoForm.section_id
      data_.student_id = this.infoForm.student_id
      data_.description = this.infoForm.description
      data_.commitment = this.infoForm.commitment// 承诺书
      data_.id = this.editId// 承诺书
      data_.delete_id = this.deleteId.join(',')
      console.log('提交信息data_：', data_)

      this.$refs['infoForm'].validate((valid) => {
        console.log('状态：', valid)
        if (valid) {
          // questionAdd(data_).then(res => {
          //   if (!res.code) {
          //     this.$message.success(res.msg)
          //     this.$router.go(-1)
          //   } else {
          //     this.$message.error(res.msg)
          //   }
          // })
          this.$post(this.api.questionnaire.examine_edit, data_).then(res => {
            if (res.code === 0) {
              this.$message.success(res.msg)
              this.$router.go(-1)
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    changeSection(option) {
      this.infoForm.class_id = ''
      this.infoForm.section_id = option
    },
    changeClass(option) {
      this.infoForm.class_id = option
    },
    changeSectionMore(option) {
      this.value1 = option
    },
    staduentchange() {
      if (this.studentRadio === 0) {
        this.dynamicTags = []
        this.dynamicTagsId = []
        this.dynamicTagsArray = {}
        this.infoForm.student_id = 0
      }
    },
    chooseStudent() {
      console.log('idname:', this.infoForm.section_id, this.infoForm.class_id)
      this.studentVisible = true
    },
    studentFn(option) {
      console.log('接受到的数据：', option)
      for (let i in option) {
        this.dynamicTags.push(option[i].name)
        this.dynamicTagsId.push(option[i].id)
        this.dynamicTagsArray = option
      }
      this.infoForm.student_id = this.dynamicTagsId.join(',')
    },
    handleClose(index) {
      this.dynamicTags.splice(index, 1)
      delete this.dynamicTagsArray[this.dynamicTagsId[index]] // 去除选中的人
      this.dynamicTagsId.splice(index, 1)
      this.infoForm.student_id = this.dynamicTagsId.join(',')
    },
    commitmentEditFn(option) {
      this.infoForm.commitment = option
    },
    commitmentBtnFn() {
      this.commitmentVisible = true
    },
    // 查看明细
    showUserQulityFn(id) {
      this.optionId = id
      this.qustionUserVisible = true
    },
    commitmentChange(index) {
      console.log('文件：', this.infoForm.body)
      if (this.infoForm.body[index].show_status === 1) {
        for (let i in this.infoForm.body) {
          if (Number(i) !== index) {
            this.infoForm.body[i].show_status = 0
          }
        }
      }
    },
    gotoExcel(index) {
      this.$http({
        method: 'get',
        url: `${this.$BASE_URL}/admin/`+this.api.task.excel + '?id=' + this.listCheck[index].id,
        responseType: 'arraybuffer'
      })
          .then(
              function (response) {
                this.fileDownload(response.data, this.listCheck[index].content)
              }.bind(this)
          )
          .catch(
              function (error) {
                alert('网络请求出错')
              }
          )
    },
    gotoExcelOnly(line, id, title) {
      console.log('内容信息：', line, id, title)
      this.$http({
        method: 'get',
        url:  `${this.$BASE_URL}/admin/`+this.api.task.sign_export + '?question_id=' + id + '&option=' + line.index,
        responseType: 'arraybuffer'
      })
          .then(
              function (response) {
                this.fileDownload(response.data, title + ',' + line.index + '.' + line.text)
              }.bind(this)
          )
          .catch(
              function (error) {
                alert('网络请求出错')
              }
          )
    },
    fileDownload(data, pushname) {
      let blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      let filename = pushname + '-填写明细.xls' || 'filename.xls'
      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, filename)
      } else {
        let blobURL = window.URL.createObjectURL(blob)
        let tempLink = document.createElement('a')
        tempLink.style.display = 'none'
        tempLink.href = blobURL
        tempLink.setAttribute('download', filename)
        if (typeof tempLink.download === 'undefined') {
          tempLink.setAttribute('target', '_blank')
        }
        document.body.appendChild(tempLink)
        tempLink.click()
        document.body.removeChild(tempLink)
        window.URL.revokeObjectURL(blobURL)
      }
    }
  }
}
</script>
<style lang="scss">


.questionlist:last-child .questionlist {
  border-bottom: 0;
}

.inlinebox {
  padding-left: 20px;
}

.infoline {
  font-size: 12px;
  color: #777;
  margin-left: 10px;
}

.ql-editor {
  max-height: 250px;
}

.el-dialog__body {
  padding: 0 20px;
}

.el-radio__label {
  /*display: none;*/
}

.warp {
  width: 80%;
  padding: 30px;
  margin: 0 auto;
}

.el-dialog__body {
  /*text-align: center;*/
}

.el-pagination {
  padding-top: 20px;
}


.iconadd {
  cursor: pointer;
  font-size: 20px;
  margin-left: 10px;
}

.iconlist {
  margin-bottom: 10px;
}

.addicon {

}

.detelicon {
  color: red;
}
</style>
